#ifdef BUILD_WITH_FACEBOOK

#include "FacebookAPIManager.h"

FacebookAPIManager::FacebookAPIManager()
: QObject(), m_currentCallId(0)
{
	m_manager = new QNetworkAccessManager(this);
}

FacebookAPIManager::~FacebookAPIManager()
{
}

bool FacebookAPIManager::callMethod(const QString& method, const QMap<QString, QString>& params)
{
	QUrl url("http://api.facebook.com/restserver.php");
	url.addQueryItem("api_key", m_apiKey);
	url.addQueryItem("method", method);
	url.addQueryItem("v", "1.0");

	if(method.indexOf("auth") < 0)
	{
		url.addQueryItem("session_key", m_sessionKey);
		url.addQueryItem("call_id", QString::number(m_currentCallId++));
	}

	QMapIterator<QString, QString> iterator(params);
	while(iterator.hasNext())
	{
		iterator.next();
		url.addQueryItem(iterator.key(), iterator.value());
	}

	QString sig;

	typedef QPair<QString, QString> StringPair;
	QMap<QString, QString> tempMap;
	
	foreach(StringPair q, url.queryItems())
	{
		tempMap.insert(q.first, q.second);
	}

	QMapIterator<QString, QString> it(tempMap);
	while(it.hasNext())
	{
		it.next();
		sig += it.key() + "=" + it.value();
	}

	sig += "cf35741c58d707124844db5706010672";

	QByteArray md5 = QCryptographicHash::hash(sig.toUtf8(), QCryptographicHash::Md5).toHex();
	QString sigMd5(md5);
	qDebug() << "sigmd5=" << sigMd5;

	url.addQueryItem("sig", sigMd5);

	QNetworkRequest request(url);
	request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/x-www-form-urlencoded"));
	request.setRawHeader("User-Agent", "FacebookAPIManager (CamWhore/1.0)");

	QNetworkReply* reply = m_manager->get(request);
	connect(reply, SIGNAL(readyRead()), this, SLOT(readData()));
	return true;
}

void FacebookAPIManager::readData()
{
	QNetworkReply* dev = static_cast<QNetworkReply*>(sender());
	QByteArray data = dev->readAll();
	QString dataStr(data);

	QNetworkRequest req = dev->request();
	QString method = req.url().queryItemValue("method");

	if(method == "auth.createToken")
	{
		QString token = dataStr.mid(1, dataStr.length() - 2);
		qDebug() << "token=" << token;

		// send out a get session

		QMap<QString, QString> params;
		params["auth_token"] = token;
		params["generate_session_secret"] = "false";

		callMethod("auth.getSession", params);
	}
	else if(method == "auth.getSession")
	{
		qDebug() << "auth.getSession:\n" << dataStr;
	}
}

void FacebookAPIManager::setApiKey(const QString& apiKey)
{
	m_apiKey = apiKey;
}

void FacebookAPIManager::setSessionKey(const QString& sessionKey)
{
	m_sessionKey = sessionKey;
}

void FacebookAPIManager::setUid(const QString& uid)
{
	m_uid = uid;
}

void FacebookAPIManager::setSecret(const QString& secret)
{
	m_secret = secret;
}

#endif
